import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import { getUserInfoApi, loginApi, userLogoutAPi } from "@/api/login"
import { type LoginRequestData, userInfoData } from "@/api/login/types/login"
import { ElMessage } from "element-plus"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  const userAccount = ref<string>("")
  const userInfo = ref<userInfoData>()

  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 设置角色数组 */
  const setRoles = (value: string[]) => {
    roles.value = value
  }
  /** 登录 */
  const login = async ({ userAccount, userPassword }: LoginRequestData) => {
    const { data } = await loginApi({ userAccount, userPassword })
    setToken(data)
    token.value = data
    await getInfo()
    setLocalUserInfo()
  }
  const setLocalUserInfo = () => {
    localStorage.setItem("user", JSON.stringify(userInfo.value))
  }
  const getLocalUserInfo = () => {
    return JSON.parse(localStorage.getItem("user"))
  }
  const removeUserInfo = () => {
    localStorage.removeItem("user")
  }

  /** 获取用户详情 */
  const getInfo = async () => {
    const { data } = await getUserInfoApi()
    console.log(data)
    userInfo.value = data
    userAccount.value = data.userAccount
    // // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
    // roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles
  }
  const userLogOut = async () => {
    const { message } = await userLogoutAPi()
    ElMessage.warning(message)
  }
  /** 切换角色 */
  /** 登出 */
  const logout = () => {
    userLogOut()
    resetToken()
    removeUserInfo()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  return {
    token,
    roles,
    userAccount,
    userInfo,
    getLocalUserInfo,
    setRoles,
    login,
    getInfo,
    logout,
    resetToken
  }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
